import React, { Component } from 'react';
import {
  Table,
  Pagination,
  Dialog,
  Button,
  Icon,
  Grid,
  Input, DatePicker, Select, Message,
} from '@alifd/next';
import { withRouter } from 'react-router-dom';
import IceContainer from '@icedesign/container';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import Img from '@icedesign/img';
import ChooseHead from '../chooseHead';
import PageHead from '../../../../components/PageHead';
import GlassTable from '../../../../components/GlassTableforStock';
import dataSource from '../../../../utils/datasource';
import { getLocalTime } from '../../../../utils/localTime';
import './index.scss';
import service from '../../../../utils/service';
import api from '../../../../utils/api.js';
import deepCopy from '../../../../utils/deepClone';

const { Row, Col } = Grid;
function TableFooter(props) {
  return (
    <div style={{ fontSize: '14px' }}>
      <span style={{ display: 'inline-block', background: '#FF6E02', padding: '10px', color: '#fff', marginRight: '20px' }}>合计：</span>
      <span style={{ marginRight: '20px' }}>库存总数量：<span style={{ color: '#D95700' }}>{props.data.sum_num}</span> </span>
      <span style={{ marginRight: '20px' }}>成本总金额：<span style={{ color: '#D95700' }}>{props.data.sum_buying}</span> </span>
      <span style={{ marginRight: '20px' }}>零售总金额：<span style={{ color: '#D95700' }}>{props.data.sum_retail}</span> </span>
    </div>
  );
}
@withRouter
export default class goodList extends Component {
  state = {
    page: 1,
    w_id: '', // 当前仓库id
    isLoading: true,
    storeList: [], // 仓库列表
    stockList: [], // 库存列表
    SingleGoodsData: [], // 详情
    countPage: 1, // 总页数
    perPage: 10, // 每页数据量
    filterData: {
      class_id: '',
      search: '',
      model: '',
      w_id: '',
    }, // 筛选条件
    Dvisible0: false, // 详情弹窗
    Dvisible1: false, // 镜片详情弹窗
    DBvisible: false,
    Rvisible: false, // 退库弹窗
    // id: '', // 列表id
    g_id: '', // 商品id
    allotFormData: {
      out_w_id: '',
      on_w_id: '',
      stock: 1,
      add_time: '',
    }, // 调拨表单
    returnFormData: {
      out_w_id: '',
      on_w_id: '',
      stock: 1,
      add_time: '',
    }, // 退库表单
    GlassData: dataSource,
    GlassTableVisible: false,
    lensType: '- / -',
    id: '', // 库存详情 商品id
    clickType: '',
    goodsType: '',
    diopter: '', // 散光度
    astigmatism: '', // 散光度
    batchNumberArr: [], // 批号
    dataCount: {}, // 统计数据
    stock_type: 1,
  };
  // 获取库存列表
  getStockList= () => {
    service({
      method: 'get',
      url: api.StockInventory,
      params: {
        w_id: this.state.filterData.w_id,
        class_id: this.state.filterData.class_id || '',
        model: this.state.filterData.model,
        search: this.state.filterData.search,
        year: this.state.filterData.year,
        month: this.state.filterData.month,
        page: this.state.page || 1,
        stock_type: this.state.stock_type,
      },
    })
      .then((res) => {
        if (res.data.code === 200) {
          const stockList = res.data.list;
          const countPage = res.data.count_page;
          const dataCount = res.data.count;
          this.setState(
            {
              stockList,
              countPage,
              isLoading: false,
              dataCount,
            }
          );
        }
      });
  }
  // 详情
 getSingleData= () => {
   service({
     method: 'get',
     url: api.GoodsInfo,
     params: {
       g_id: this.state.g_id || '',
     },
   })
     .then((res) => {
       if (res.data.code === 200) {
         const type = res.data.goods_info.goods_type;
         if (type === 0) {
           this.setState(
             {
               SingleGoodsData: res.data.goods_info,
               Dvisible0: true,
             }
           );
         } else {
           this.setState(
             {
               SingleGoodsData: res.data.goods_info,
               Dvisible1: true,
             }
           );
         }
       }
     });
 }
// 获取仓库列表
getStoreList= () => {
  service({
    method: 'get',
    url: api.StoreList,
  })
    .then((res) => {
      const data = res.data.list;
      const storeList = [];
      if (data.length !== 0) {
        data.forEach((item) => {
          let obj = {};
          obj = { label: item.name, value: item.id };
          storeList.push(obj);
        });
      }
      this.setState(
        {
          storeList,
        }
      );
    });
}

// 获取批号
getBatchNumber= () => {
  const data = this.state;
  service({
    method: 'get',
    url: api.getBatchNumber,
    params: {
      stock_id: data.id,
      diopter: data.diopter,
      astigmatism: data.astigmatism,
      lens_type: data.lensType,
    },
  })
    .then((res) => {
      // console.log(res);
      if (res.data.code === 200) {
        const oList = res.data.lens_list;
        const batchNumberArr = [];
        oList.forEach((item) => {
          batchNumberArr.push({ label: item.batch_number, value: item.id });
        });
        const clickType = this.state.clickType;
        if (clickType == 1) {
          this.setState(
            {
              batchNumberArr,
              DBvisible: true,
            }
          );
        } else {
          this.setState(
            {
              batchNumberArr,
              Rvisible: true,
            }
          );
        }
      }
    });
}
componentDidMount() {
  this.getStockList();
  this.getStoreList();
}
// 获取库存数据
getStock=() => {
  // console.log(this.state.lensType);
  service({
    method: 'get',
    url: api.StockInventoryDetail,
    params: {
      i_id: this.state.id,
      lens_type: this.state.lensType,
    },
  })
    .then((res) => {
      console.log(res);
      if (res.data.code === 200) {
        const GlassData = deepCopy(dataSource);
        const data = res.data.list;
        // console.log(data);
        GlassData.forEach((item) => {
          data.forEach((obj) => {
            const keyName = `number${obj[1].replace('.', '')}`;
            if (obj[0] == item.屈光度) {
              // console.log(obj);
              item[keyName] = obj[2];
            }
          });
        });
  
        this.setState({
          GlassData,
          GlassTableVisible: true,
        }, () => {

        }
        );
      } else {
        Message.error(res.msg);
      }
    });
}
  handlePaginationChange = (page) => {
    this.setState(
      {
        page,
        isLoading: true,
      },
      () => {
        this.getStockList();
      }
    );
  };

  handleFilterChange = (value) => {
    this.setState(
      {
        filterData: {
          class_id: value.class_id || '',
          model: value.model || '',
          search: value.search || '',
          w_id: value.w_id || '',
          year: value.year,
          month: value.month,
        },
        page: 1,
        isLoading: true,
      }, () => {
        // console.log(this.state.filterData);
        this.getStockList();
      }
    );
  };

  handleDetail = (record) => {
    this.setState(
      {
        id: record.id,
        g_id: record.g_id,
        goodsType: record.goods_type,
      }, () => {
        this.getSingleData();
      }
    );
  };
  onClose = () => {
    this.setState(
      {
        Dvisible0: false,
        Dvisible1: false,
        DBvisible: false,
        Rvisible: false,
        allotFormData: {
          out_w_id: '',
          on_w_id: '',
          stock: 1,
          add_time: '',
        }, // 调拨表单
        returnFormData: {
          out_w_id: '',
          on_w_id: '',
          stock: 1,
          add_time: '',
        }, // 退库表单
      }
    );
  }
  // handleDownload = () => {
  //   window.location.href = `${api.StockQuery}?excel=1&search=${this.state.filterData.search}&w_id=${this.state.w_id}&class_id=${this.state.filterData.class_id}&model=${this.state.filterData.model}`;
  // }
  renderOper = (value, index, record) => {
    return (
      <div>
        <div>
          <a style={styles.link.detail} onClick={() => { this.handleDetail(record); }}>
          详情
          </a>
          {record.goods_type == 1 ? (<span><span style={styles.separator} /><a style={styles.link.stock} onClick={() => { this.handleStock(record); }}>库存</a></span>) : null}
        </div>
      </div>
    );
  };
  renderCover = (value, index, record) => {
    const type = 'contain';
    let length = 0;
    let src;
    if (record.goods_img) {
      length = record.goods_img.length;
      src = `${api.uri}${record.goods_img[0]}`;
    }

    return (
      <div>
        {length > 0 ? (<div>
          <Img
            enableAliCDNSuffix={false}
            width={60}
            height={60}
            src={src}
            type={type}
            style={{ verticalAlign: 'middle' }}
          />
                       </div>) : null}
      </div>
    );
  };

  // 弹窗新加方法

  // 关闭
  handleClose= () => {
    this.setState(
      {
        GlassTableVisible: false,
      }
    );
  }
  // 切换镜片类型
  handleRadioChange= (value) => {
    this.setState(
      {
        lensType: value,
      }, () => {
        this.getStock();
      }
    );
  }
  // 获取库存表格
  handleStock=(record) => {
    this.setState(
      {
        id: record.id,
        lensType: '- / -',
        clickType: 0,
      }, () => {
        this.getStock();
      }
    );
  }
  // 双击事件
  handleDoubleClick=(valueKey, quguang) => {
    return false;
  }
  render() {
    const { isLoading, stockList, page, countPage, perPage, SingleGoodsData, storeList, GlassData, GlassTableVisible, goodsType, batchNumberArr } = this.state;

    return (
      <div style={styles.container}>
        <ChooseHead filterChange={this.handleFilterChange} storeList={storeList} />
        <PageHead title="库存盘点列表" buttonText="导出Excel" onClick={this.handleDownload} />
        <IceContainer style={{ paddingBottom: '0' }}>
          <Table loading={isLoading} dataSource={stockList} hasBorder={false}>
            <Table.Column title="封面图" dataIndex="goods_img" cell={this.renderCover} />
            <Table.Column title="商品编码" dataIndex="goods_bar_code" />
            <Table.Column title="品牌" dataIndex="goods_class_name" />
            <Table.Column title="商品名称" dataIndex="goods_name" />           
            <Table.Column title="仓库名称" dataIndex="name" />
            <Table.Column title="型号" dataIndex="model" />
            <Table.Column title="色号/膜层" dataIndex="color_layer" />
            <Table.Column title="数量" dataIndex="stock" />
            <Table.Column title="零售价" dataIndex="retail_price" />
            <Table.Column title="进货价" dataIndex="buying_price" />
            {/* <Table.Column title="镜片类型" dataIndex="lens_type" /> */}
            <Table.Column title="折射率" dataIndex="lens_type" />
            {/* <Table.Column title="屈光度" dataIndex="diopter" />
            <Table.Column title="散光度" dataIndex="astigmatism" /> */}
            <Table.Column title="折扣" dataIndex="rebate" />
            {/* <Table.Column title="生产批号" dataIndex="batch_number" />
            <Table.Column title="到期日期" dataIndex="due_time" /> */}
            <Table.Column title="操作" cell={this.renderOper} />
          </Table>
          <TableFooter data={this.state.dataCount} />
          {/* 商品信息详情 */}
          <Dialog
            visible={this.state.Dvisible0}
            onClose={this.onClose}
            footer={<Button type="primary" onClick={this.onClose} className="dialogButton EditBtn">确定</Button>}
            footerAlign="center"
            id="DDialog"
            style={{ marginTop: '25px' }}
          >
            <h3 className="titleWrap"><span className="dialogTitle">商品信息详情信息</span></h3>
            <IceContainer className="dialogContent">
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">商品条码:</Col>
                <Col span="6" >{SingleGoodsData.goods_bar_code}</Col>

                <Col span="6" className="listNameQ">供应商:</Col>
                <Col span="6">{SingleGoodsData.name}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">商品类别:</Col>
                <Col span="6" >{SingleGoodsData.class_name}</Col>

                <Col span="6" className="listNameQ">商品名称:</Col>
                <Col span="6">{SingleGoodsData.goods_name}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                
                <Col span="6" className="listNameQ">型号:</Col>
                <Col span="6">{SingleGoodsData.model}</Col>
                <Col span="6" className="listNameQ">ADD:</Col>
                <Col span="6" >{SingleGoodsData.ADD}</Col>
              </Row>

              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                
                <Col span="6" className="listNameQ">颜色/膜层:</Col>
                <Col span="6" >{SingleGoodsData.color_layer}</Col>
                <Col span="6" className="listNameQ">特殊参数:</Col>
                <Col span="6">{SingleGoodsData.case_value}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
               
                <Col span="6" className="listNameQ">单位:</Col>
                <Col span="6" >{SingleGoodsData.unit}</Col>
                <Col span="6" className="listNameQ">规格:</Col>
                <Col span="6">{SingleGoodsData.spec}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">零售价:</Col>
                <Col span="6">{SingleGoodsData.retail_price}</Col>
                <Col span="6" className="listNameQ">进货价:</Col>
                <Col span="6" >{SingleGoodsData.buying_price}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">折扣率:</Col>
                <Col span="6">{SingleGoodsData.rebate}</Col>
                <Col span="6" className="listNameQ">积分率:</Col>
                <Col span="6">{SingleGoodsData.integral_rate}</Col>
              </Row>
            </IceContainer>
          </Dialog>
          {/* 库存详情 */}
          <GlassTable lensType={this.state.lensType} handleDoubleClick={this.handleDoubleClick} handleClose={this.handleClose} handleRadioChange={this.handleRadioChange} dataSource={GlassData} GlassTableVisible={GlassTableVisible} />


          <Dialog
            visible={this.state.Dvisible1}
          // autoFocus
            onClose={this.onClose}
            footer={<Button type="primary" onClick={this.onClose} className="dialogButton EditBtn">确定</Button>}
            footerAlign="center"
            id="DDialog"
            style={{ marginTop: '25px' }}
          >
            <h3 className="titleWrap"><span className="dialogTitle">商品信息详情信息</span></h3>
            <IceContainer className="dialogContent">
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">商品条码:</Col>
                <Col span="6" >{SingleGoodsData.goods_bar_code}</Col>

                <Col span="6" className="listNameQ">供应商:</Col>
                <Col span="6">{SingleGoodsData.name}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">商品类别:</Col>
                <Col span="6" >{SingleGoodsData.class_name}</Col>

                <Col span="6" className="listNameQ">商品名称:</Col>
                <Col span="6">{SingleGoodsData.goods_name}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">ADD:</Col>
                <Col span="6" >{SingleGoodsData.ADD}</Col>

                <Col span="6" className="listNameQ">折射率:</Col>
                <Col span="6">{SingleGoodsData.refractivity}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">是否渐进:</Col>
                <Col span="6" >{SingleGoodsData.is_gradual}</Col>

                <Col span="6" className="listNameQ">是否球面:</Col>
                <Col span="6">{SingleGoodsData.is_sphere}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                

                <Col span="6" className="listNameQ">型号:</Col>
                <Col span="6">{SingleGoodsData.model}</Col>
                <Col span="6" className="listNameQ">颜色/膜层:</Col>
                <Col span="6" >{SingleGoodsData.color_layer}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                

                <Col span="6" className="listNameQ">特殊参数:</Col>
                <Col span="6">{SingleGoodsData.case_value}</Col>
                <Col span="6" className="listNameQ">单位:</Col>
                <Col span="6" >{SingleGoodsData.unit}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
              <Col span="6" className="listNameQ">进货价:</Col>
                <Col span="6" >{SingleGoodsData.buying_price}</Col>

                <Col span="6" className="listNameQ">零售价:</Col>
                <Col span="6">{SingleGoodsData.retail_price}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
               

                <Col span="6" className="listNameQ">折扣率:</Col>
                <Col span="6">{SingleGoodsData.rebate}</Col>
                <Col span="6" className="listNameQ">积分率:</Col>
                <Col span="6">{SingleGoodsData.integral_rate}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
               
                <Col span="6" className="listNameQ">生产企业:</Col>
                <Col span="18">{SingleGoodsData.esta_person}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">生产许可证号:</Col>
                <Col span="6">{SingleGoodsData.pro_number}</Col>
                <Col span="6" className="listNameQ">生产许可证有效期至:</Col>
                <Col span="6">{SingleGoodsData.pro_time}</Col>

              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">经营许可证号:</Col>
                <Col span="6">{SingleGoodsData.ope_number}</Col>
                <Col span="6" className="listNameQ">经营许可证有效期至:</Col>
                <Col span="6">{SingleGoodsData.ope_time}</Col>
              </Row>

              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">注册证号:</Col>
                <Col span="6">{SingleGoodsData.reg_number}</Col>
                <Col span="6" className="listNameQ">注册证有效期至:</Col>
                <Col span="6">{SingleGoodsData.reg_time}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">有效期（月）:</Col>
                <Col span="6">{SingleGoodsData.term_time}</Col>
                <Col span="6" className="listNameQ">国际医疗器械类别编号:</Col>
                <Col span="6">{SingleGoodsData.medical_number}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">医疗器械名称:</Col>
                <Col span="6">{SingleGoodsData.medical_name}</Col>
                <Col span="6" className="listNameQ">预留1:</Col>
                <Col span="6">{SingleGoodsData.m_reserve_one}</Col>
              </Row>
              <Row wrap width="100" style={{ marginBottom: '15px' }}>
                <Col span="6" className="listNameQ">预留2:</Col>
                <Col span="6">{SingleGoodsData.m_reserve_two}</Col>
              </Row>
            </IceContainer>
          </Dialog>
        </IceContainer>
        <Pagination
          style={styles.pagination}
          current={page}
          onChange={this.handlePaginationChange}
          total={countPage * perPage}
        />
      </div>
    );
  }
}

const styles = {
  container: {
    padding: '0 0px 20px',
  },
  listTitle: {
    textAlign: 'left',
    lineHeight: '40px',
    fontSize: '20px',
    color: '#333333',
    width: '140px',
    height: '40px',
  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
    allot: {
      color: '#8272EC',
      cursor: 'pointer',
    },
    detail: {
      color: '#5584FF',
      cursor: 'pointer',
    },
    return: {
      color: '#FF3000',
      cursor: 'pointer',
    },
    stock: {
      color: '#ff9d0c',
      cursor: 'pointer',
    },
  },
  separator: {
    margin: '0 8px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    marginTop: '20px',
    textAlign: 'center',
  },
  col: {
    margin: '10px 0 10px 0',
    float: 'left',
  },
  Select: {
    float: 'left',
    width: '200px',
    height: '38px',
  },
  date: {
    float: 'left',
    height: '38px',
  },
  SelectLabel: {
    fontSize: '14px',
    lineHeight: '40px',
    float: 'left',
    margin: '0 10px 0 0',
    padding: '0',
    color: '#666',
    textAlign: 'left',
    minWidth: '60px',
  },
  search: {
    width: '300px',
  },
  row: {
    marginBottom: '20px',
  },
  input: {
    float: 'left',
  },
};
